var sel_cmemo_obj = null;
var cmoDetail_tabview = null;
from_search = false;

function open_sel_cmemo(cmemonum){
	open_cmemo_detail(cmemonum);
}

function open_cmemo_detail(cmemonum){
	u_hideAllSections();
	u_safeShowElement('cmemodetails_div');
	
	if(cmoDetail_tabview == null){
		cmoDetail_tabview = new YAHOO.widget.TabView("cmodetails_div_inner");
	}
	cmoDetail_tabview.set('activeIndex',0);
	
	sel_cmemo_obj = null;
	
	if(search_found_cache && search_found_cache != null && search_found_cache.documentType == "CMEMO"){
		for(var i=0;i<search_found_cache.length;i++){
			if(search_found_cache[i].creditMemoNumber == cmemonum){
				sel_cmemo_obj = search_found_cache[i];
				from_search = true;
				break;
			}
		}
	}
	
	try{
		if(sel_cmemo_obj == null){
			if(cmemo_sent_cache && cmemo_sent_cache != null && cmemo_sent_cache.length > 0){
				for(var i=0;i<cmemo_sent_cache.length;i++){
					if(cmemonum == cmemo_sent_cache[i].creditMemoNumber){
						sel_cmemo_obj = cmemo_sent_cache[i];
						assignAttachmentComponent("attachmentComponetPlaceHolder8");
						assignCommentsComponent("commentComponetPlaceHolder8");
						 break;
					}
					
				}
			}
		}
	}catch(ex){
	}
	
	try{
		if(sel_cmemo_obj == null){
			if(cmemo_recd_cache && cmemo_recd_cache != null && cmemo_recd_cache.length > 0){
				for(var i=0;i<cmemo_recd_cache.length;i++){
					if(cmemonum == cmemo_recd_cache[i].creditMemoNumber){
						sel_cmemo_obj = cmemo_recd_cache[i];
						 break;
					}
				}
			}
		}
	}catch(ex){}
	
	
	if(cmemo_sent_cache && cmemo_sent_cache != null){
		for(var i=0;i<cmemo_sent_cache.length;i++){
			if(sel_cmemo_obj.creditMemoNumber == cmemo_sent_cache[i].creditMemoNumber){
				$("cmo_updateAction").style.display = "block";
				assignAttachmentComponent("attachmentComponetPlaceHolder8");
				assignCommentsComponent("commentComponetPlaceHolder8");
				dwr.util.setValue('target_comp_comment',"UPDATE_CMO");
				dwr.util.setValue('target_comp_attachment',"UPDATE_CMO");
				$("attph5_hdr").style.display = "block";
				$("attcm5_hdr").style.display = "block";
				break;
			} else{
				$('attachmentComponent').style.display='none';
				$('commentsComponent').style.display='none';
				$("cmo_updateAction").style.display = "none";
				$("attph5_hdr").style.display = "none";
				$("attcm5_hdr").style.display = "none";
			}
		}
	}else{
		$('attachmentComponent').style.display='none';
		$('commentsComponent').style.display='none';
		$("cmo_updateAction").style.display = "none";
		$("attph5_hdr").style.display = "none";
		$("attcm5_hdr").style.display = "none";
	}
	
	populate_creditmemo_details(sel_cmemo_obj);
	
	if(!isNavigationFromBackButton){
		var functionPointerObj = new Object();
		functionPointerObj.functionName = "open_cmemo_detail("+"'"+cmemonum+"'"+")";
		navigationStateArray.push(functionPointerObj);
	}
	
}

function populate_creditmemo_details(sel_cmemo_obj){
	dwr.util.setValue('cmemodetails_num',"");
	dwr.util.setValue('cmemodetails_date',"");
	dwr.util.setValue('cmemodetails_amt',"");
	dwr.util.setValue('cmemo_buyer_name',"");
	dwr.util.setValue('cmemo_supp_name',"");
	
	if(sel_cmemo_obj && sel_cmemo_obj != null){
		dwr.util.setValue('cmemodetails_num',sel_cmemo_obj.creditMemoNumber);
		dwr.util.setValue('cmemodetails_date',format_date(sel_cmemo_obj.creditMemoDate));
		dwr.util.setValue('cmemodetails_amt',sel_cmemo_obj.totalCreditMemoAmount);
		dwr.util.setValue('cmemo_buyer_name',sel_cmemo_obj.creditMemoToCompanyName);
		dwr.util.setValue('cmemo_supp_name',sel_cmemo_obj.creditMemoFromCompanyName);
		populate_attachmentForSelectedCMEMO(sel_cmemo_obj);
		populate_commentsForSelectedCMEMO(sel_cmemo_obj);
		populate_invoiceForSelectedCMEMO(sel_cmemo_obj);
		cmemo_render_lineitems(sel_cmemo_obj);
		//Get history of the payment
		populate_cmoh_table(sel_cmemo_obj.creditMemoHistory);

	}
		
}

function populate_attachmentForSelectedCMEMO(cmemo){
	try{
	dwr.util.removeAllRows("cmemoDisplayattachments_tbody", {
		filter : function(tr) {
			return (tr.id != "cmemoDisplayattachments_pattern");
		}
	});	
	if(cmemo.creditmemoAttachmentIds != null){
	
		for(var i=0;i<cmemo.creditmemoAttachmentIds.length;i++){
			var responseText = cmemo.creditmemoAttachmentIds[i];
			var ids = i + ""
			dwr.util.cloneNode('cmemoDisplayattachments_pattern', {idSuffix : ids});
			$("cmemoDispalyattachments_link"+ids).setAttribute("href",'javascript:openAttachmentPanel("http://www.atsocii.com'+responseText.split(":")[1]+'");');
			$("cmemoDispalyattachments_link"+ids).innerHTML = responseText.split(":")[3];
			$("cmemoDisplayattachments_pattern"+ids).style.display = '';
		}
	}
	}catch(ex){}
}

function populate_commentsForSelectedCMEMO(cmemo){
	
	try{
		dwr.util.removeAllRows("cmemoDisplaycomments_tbody", {
			filter : function(tr) {
				return (tr.id != "cmemoDisplaycomments_pattern");
			}
		});
		
		if(cmemo.creditMemoComments != null){
		
			for(var i=0;i<cmemo.creditMemoComments.length;i++){
				var responseText = cmemo.creditMemoComments[i];
				var ids = i + ""
				dwr.util.cloneNode('cmemoDisplaycomments_pattern', {idSuffix : ids});
				$("cmemoDisplaycomment_text"+ids).innerHTML = responseText;
				$("cmemoDisplaycomments_pattern"+ids).style.display = '';
			}
		}
		}catch(ex){}
}

function populate_invoiceForSelectedCMEMO(cmemo){
	try{
	create_invoiceForSelectedCMEMO();
	clear_invoiceForSelectedCMEMO();
	var slectedInvoiceObjectArray = new Array();
	if(inv_recdcache && inv_recdcache != null){
		for(var j=0;j<inv_recdcache.length;j++){
			if(cmemo.invoiceNumber == inv_recdcache[j].invoiceNumber){
				slectedInvoiceObjectArray.push(inv_recdcache[j]);
			}
		}
	}
	if(invsent_cache && invsent_cache != null){
		for(var k=0;k<invsent_cache.length;k++){
			if(cmemo.invoiceNumber == invsent_cache[k].invoiceNumber){
				slectedInvoiceObjectArray.push(invsent_cache[k]);
			}
		}
	}
	
	
	invoiceForSelectedcmemo_yui_table_instance.addRows(slectedInvoiceObjectArray);
	} catch(ex){
		create_invoiceForSelectedCMEMO();
		clear_invoiceForSelectedCMEMO();
	}
}
var invoiceForSelectedcmemo_yui_table_instance = null;
function create_invoiceForSelectedCMEMO() {
	if(invoiceForSelectedcmemo_yui_table_instance == null){
	var invrcolumnDefs = [ {
		key : "invoiceNumber",
		label : "Invoice#",
		sortable : true,
		formatter : "hlinkFormatter"
	}, {
		key : "supplierNameText",
		label : "Supplier",
		sortable : true
	}, {
		key : "invoiceSubmittedDate",
		label : "Invoice Date",
		formatter: "date",
		sortable : true
	} , {
		key : "purchaseOrderNumber",
		label : "PO#"
	}, {
		key : "totalInvoiceAmount",
		label : "Amount",
		formatter: "currency"
	} ];

	var invrDataSource = new YAHOO.util.DataSource();
	invrDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
	
	
	invoiceForSelectedcmemo_yui_table_instance = new YAHOO.widget.DataTable("cmemodetails_invoice_yui_table",invrcolumnDefs,invrDataSource,{});
	invoiceForSelectedcmemo_yui_table_instance.set("selectionMode", "single");
	invoiceForSelectedcmemo_yui_table_instance.subscribe("rowClickEvent",
		invoiceForSelectedcmemo_yui_table_instance.onEventSelectRow);
	}

}

function clear_invoiceForSelectedCMEMO() {
	if (invoiceForSelectedcmemo_yui_table_instance != null && invoiceForSelectedcmemo_yui_table_instance.getRecordSet() != null && invoiceForSelectedcmemo_yui_table_instance.getRecordSet().getLength() > 0) {
		var length = invoiceForSelectedcmemo_yui_table_instance.getRecordSet().getLength();
		if (length > 0) {
			invoiceForSelectedcmemo_yui_table_instance.deleteRows(0, length);
		}
	}
}

var cmemo_litems_yui_instance = null;

function clearlineitemsCmemoTable(){
	if(cmemo_litems_yui_instance != null && cmemo_litems_yui_instance.getRecordSet() != null && cmemo_litems_yui_instance.getRecordSet().getLength() > 0){
		cmemo_litems_yui_instance.deleteRows(0,cmemo_litems_yui_instance.getRecordSet().getLength());
	}
}

var cmemolineItemReadOnlycolumnDefs = [ {
	key : "creditMemoLineNumber",
	label : "Line",
	width : "50px"
	
}, {
	key : "partNumber",
	label : "Part Number",
	width : "50px"
	
},{
	key : "invoiceLineDescription",
	label : "Description",
	width : "50px"
}, {
	key : "quantity",
	label : "Quantity",
	width : "50px"
	
} ,{
	key : "uomSymbol",
	label : "Unit Of Measure",
	width : "50px"
} ,{
	key : "unitPrice",
	label : "Unit Price",
	width : "50px"
}  ,{
	key : "lineAmount",
	label : "Line Total",
	width : "50px"
}  ]

function cmemo_render_lineitems(cmemo){
	if(cmemo_litems_yui_instance == null){
		var liDataSource = new YAHOO.util.DataSource();
		liDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		cmemo_litems_yui_instance = new YAHOO.widget.DataTable("cmemolidetails_yui_table",cmemolineItemReadOnlycolumnDefs,liDataSource,{});
		cmemo_litems_yui_instance.set("selectionMode", "single");
		cmemo_litems_yui_instance.subscribe("rowClickEvent",
				cmemo_litems_yui_instance.onEventSelectRow);
	}
	clearlineitemsCmemoTable();
	if(cmemo.creditMemoLines && cmemo.creditMemoLines != null && cmemo.creditMemoLines.length > 0){
		cmemo_litems_yui_instance.addRows(cmemo.creditMemoLines);
	}
}

function updateCreditMemo(){
	
	try{
		var poNewAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if($('poattachments_check'+ip+'').checked){
					poNewAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		
		
		
		var poNewCmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if($('pocomment_check'+iq+'').checked){
					poNewCmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		
	}catch(ex){}
	
	var dwrCallMetaData = {
			callback : success_updatecmo,
			exceptionHandler : exception_updatecmo_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

	DWR_Invoice.updateCreditMemo(sel_cmemo_obj.creditMemoNumber,poNewAtchArr,poNewCmtarr,loggedinuser,dwrCallMetaData);
	
}

function success_updatecmo(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			var cmonum = dwrresp.objRespOrError.creditMemoNumber;
			if(cmemo_sent_cache && cmemo_sent_cache != null){
				for(var i=0;i<cmemo_sent_cache.length;i++){
					if(cmemo_sent_cache[i].creditMemoNumber == cmonum){
						cmemo_sent_cache[i] = dwrresp.objRespOrError ;
						break;
					}
				}
			}		
			
			if(cmemo_recd_cache && cmemo_recd_cache != null){
				for(var i=0;i<cmemo_recd_cache.length;i++){
					if(cmemo_recd_cache[i].creditMemoNumber == cmonum){
						cmemo_recd_cache[i] = dwrresp.objRespOrError ;
						break;
					}
				}
			}
			
			open_sel_cmemo(cmonum);
			alert("Credit Memo Updated.");
		}
	} else{
		alert("Credit Memo could not be Updated. Please try again.");
	}
}

function exception_updatecmo_handler(resp){
	//console.log(resp);
}

var cmoh_yui_table_instance = null;
var cmohcolumnDefs = [ {
	key : "creditMemoNumber",
	label : "creditMemo#"
}, {
	key : "creditMemoVersion",
	label : "creditMemo Version",
	formatter: "hlinkFormatter"	
},{
	key : "creditMemoToCompanyName",
	label : "Buyer",
	sortable : true
}, {
	key : "lastModifiedDate",
	label : "Last Modified Date",
	formatter: formatLastUpdateDate,
	sortable : true
}, {
	key : "lastModifiedBy",
	label : "Last Modified By",
	formatter: "date",
	sortable : true
} , {
	key : "totalCreditMemoAmount",
	label : "creditMemo Amount",
	formatter: "currency"
}];

function create_cmoh_results_table() {
	if(cmoh_yui_table_instance == null){
		var cmosDataSource = new YAHOO.util.DataSource();
		cmosDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		cmoh_yui_table_instance = new YAHOO.widget.DataTable("cmo_history_yui_table",cmohcolumnDefs,cmosDataSource,{});
		cmoh_yui_table_instance.set("selectionMode", "single");
		cmoh_yui_table_instance.subscribe("rowClickEvent",cmoh_yui_table_instance.onEventSelectRow);
	}
}

function clear_cmoh_results_table() {
	if (cmoh_yui_table_instance != null) {
		var length = cmoh_yui_table_instance.getRecordSet().getLength();
		if (length > 0) {
			cmoh_yui_table_instance.deleteRows(0, length);
		}
	}
}

function populate_cmoh_table(history){
	create_cmoh_results_table();
	clear_cmoh_results_table();
	if(history != undefined && history != null && history.length > 0){
		/*for(var i=0;i<history.length;i++){
			history[i].clientNameText = sel_po_cache.clientNameText;
		}*/
		cmoh_yui_table_instance.addRows(history);
	}
}

function getcmoverfrom_cache(ver){
	var ret = null;
	if(sel_cmemo_obj.creditMemoHistory && sel_cmemo_obj.creditMemoHistory != null && sel_cmemo_obj.creditMemoHistory.length > 0){
		for(var idx=0; idx<sel_cmemo_obj.creditMemoHistory.length;idx++){
			if(sel_cmemo_obj.creditMemoHistory[idx].creditMemoVersion == ver){
				ret = sel_cmemo_obj.creditMemoHistory[idx];
				ret.creditMemoHistory = sel_cmemo_obj.creditMemoHistory;
				break;
			}
		}
	}
	
	return ret;
}

function open_sel_cmo_ver(ver){
	u_hideAllSections();
	u_safeShowElement('cmemodetails_div');
	
	if(cmoDetail_tabview == null){
		cmoDetail_tabview = new YAHOO.widget.TabView("cmodetails_div_inner");
	}
	cmoDetail_tabview.set('activeIndex',0);
	
	sel_cmemo_obj = getcmoverfrom_cache(ver);
	
	populate_creditmemo_details(sel_cmemo_obj);
	
	if(cmemo_sent_cache && cmemo_sent_cache != null ){
		for(var i=0;i<cmemo_sent_cache.length;i++){
			if(sel_cmemo_obj.creditMemoNumber == cmemo_sent_cache[i].creditMemoNumber
					&& sel_cmemo_obj.creditMemoVersion == cmemo_sent_cache[i].creditMemoVersion){
				$("cmo_updateAction").style.display = "block";
				assignAttachmentComponent("attachmentComponetPlaceHolder8");
				assignCommentsComponent("commentComponetPlaceHolder8");
				dwr.util.setValue('target_comp_comment',"UPDATE_cmo");
				dwr.util.setValue('target_comp_attachment',"UPDATE_cmo");
				$("attph5_hdr").style.display = "block";
				$("attcm5_hdr").style.display = "block";
				break;
			} else{
				$('attachmentComponent').style.display='none';
				$('commentsComponent').style.display='none';
				$("cmo_updateAction").style.display = "none";
				$("attph5_hdr").style.display = "none";
				$("attcm5_hdr").style.display = "none";
			}
		}
	}else{
		$('attachmentComponent').style.display='none';
		$('commentsComponent').style.display='none';
		$("cmo_updateAction").style.display = "none";
		$("attph5_hdr").style.display = "none";
		$("attcm5_hdr").style.display = "none";
	}
}

function showasxml_cmo(){
	var data = "";
	if(sel_cmemo_obj && sel_cmemo_obj != null){
		data = sel_cmemo_obj.creditMemoXml;
	}
	showxmldata(data);
}